import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import store from '@/store';

Vue.use(Router)
// mode: (window && window.process && window.process.type === 'renderer') ? 'hash' : 'history',
const router = new Router({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  const token = store.getters.token
  const role = store.getters.role // 如 'admin' 或 'user'

  if (!token) {
    // 未登录，只放行白名单
    const whiteList = ['/login', '/register']
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 已登录：判断是否需要权限 && 判断角色是否匹配
    if (to.meta.requiresAuth) {
      if (to.meta.roles && !to.meta.roles.includes(role)) {
        next('/403') // 权限不足页
      } else {
        next()
      }
    } else {
      next()
    }
  }
})

export default router
